﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Zgq.CommonTools
{
    public class SqlHelper
    {
        #region //ExecteNonQuery方法
        /// <summary>
        ///执行一个不需要返回值的SqlCommand命令，通过指定专用的连接字符串。
        /// 使用参数数组形式提供参数列表 
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                return ExecteNonQuery(conn, cmdType, cmdText, commandParameters);
            }
        }

        public static int ExecteNonQuery(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecteNonQuery(conn, null, cmdType, cmdText, commandParameters);
        }

        /// <summary>
        ///执行一个不需要返回值的SqlCommand命令，通过指定专用的连接字符串。
        /// 使用参数数组形式提供参数列表 
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecteNonQuery(SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            SqlCommand cmd = new SqlCommand();
            //通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
            PrepareCommand(cmd, conn, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            //清空SqlCommand中的参数列表
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        ///存储过程专用
        /// </summary>
        /// <param name="cmdText">存储过程的名字</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecteNonQueryProducts(string connectionString, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecteNonQuery(connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
        }

        /// <summary>
        ///Sql语句专用
        /// </summary>
        /// <param name="cmdText">T_Sql语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecteNonQueryText(string connectionString, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecteNonQuery(connectionString, CommandType.Text, cmdText, commandParameters);
        }

        #endregion

        #region//GetTable方法

        /// <summary>
        /// 执行一条返回结果集的SqlCommand，通过一个已经存在的数据库连接
        /// 使用参数数组提供参数
        /// </summary>
        /// <param name="connecttionString">一个现有的数据库连接</param>
        /// <param name="cmdTye">SqlCommand命令类型</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
        public static DataTable GetTable(string connecttionString, CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
        {
            using (SqlConnection conn = new SqlConnection(connecttionString))
            {
                return GetTable(conn, cmdTye, cmdText, commandParameters);
            }
        }

        /// <summary>
        /// 执行一条返回结果集的SqlCommand，通过一个已经存在的数据库连接
        /// 使用参数数组提供参数
        /// </summary>
        /// <param name="connecttionString">一个现有的数据库连接</param>
        /// <param name="cmdTye">SqlCommand命令类型</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
        public static DataTable GetTable(SqlConnection conn, CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                DataSet ds = new DataSet();
                PrepareCommand(cmd, conn, null, cmdTye, cmdText, commandParameters);
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds);
                DataTable table = null;
                if (ds != null && ds.Tables.Count > 0)
                    table = ds.Tables[0];
                return table;
            }
        }

        /// <summary>
        /// Sql语句专用
        /// </summary>
        /// <param name="cmdText"> T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
        public static DataTable GetTable(string connecttionString, string cmdText, SqlParameter[] commandParameters)
        {
            return GetTable(connecttionString, CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// Sql语句专用
        /// </summary>
        /// <param name="cmdText"> T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
        public static DataTable GetTable(SqlConnection connecttion, string cmdText, SqlParameter[] commandParameters)
        {
            return GetTable(connecttion, CommandType.Text, cmdText, commandParameters);
        }
        #endregion

        /// <summary>
        /// 为执行命令准备参数
        /// </summary>
        /// <param name="cmd">SqlCommand 命令</param>
        /// <param name="conn">已经存在的数据库连接</param>
        /// <param name="trans">数据库事物处理</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">Command text，T-SQL语句 例如 Select * from Products</param>
        /// <param name="cmdParms">返回带参数的命令</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {
            //判断数据库连接状态
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandTimeout = 1800;

            //判断是否需要事物处理
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }


        public static SqlDataReader ExecuteReader(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                throw;
            }
        }

        #region//ExecuteDataSet方法

        /// <summary>
        /// return a dataset
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>return a dataset</returns>
        public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                    SqlDataAdapter da = new SqlDataAdapter();
                    DataSet ds = new DataSet();
                    da.SelectCommand = cmd;
                    da.Fill(ds);
                    return ds;
                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 返回一个DataSet
        /// </summary>
        /// <param name="cmdText">存储过程的名字</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>return a dataset</returns>
        public static DataSet ExecuteDataSetProducts(string connectionString, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteDataSet(connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
        }

        /// <summary>
        /// 返回一个DataSet
        /// </summary>
        /// <param name="cmdText">T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>return a dataset</returns>
        public static DataSet ExecuteDataSetText(string connectionString, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteDataSet(connectionString, CommandType.Text, cmdText, commandParameters);
        }

        public static DataView ExecuteDataSet(string connectionString, string sortExpression, string direction, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                    SqlDataAdapter da = new SqlDataAdapter();
                    DataSet ds = new DataSet();
                    da.SelectCommand = cmd;
                    da.Fill(ds);
                    DataView dv = ds.Tables[0].DefaultView;
                    dv.Sort = sortExpression + " " + direction;
                    return dv;
                }
            }
            catch
            {

                throw;
            }
        }
        #endregion

        #region // ExecuteScalar方法

        /// <summary>
        /// 返回第一行的第一列
        /// </summary>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个对象</returns>
        public static object ExecuteScalar(string connectionString, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteScalar(connectionString, CommandType.Text, cmdText, commandParameters);
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, SqlTransaction trans, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, trans, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        #endregion

        /// <summary>
        /// 检查是否存在
        /// </summary>
        /// <param name="strSql">Sql语句</param>
        /// <param name="cmdParms">参数</param>
        /// <returns>bool结果</returns>
        public static bool Exists(string connectionString, string strSql, params SqlParameter[] cmdParms)
        {
            int cmdresult = Convert.ToInt32(ExecuteScalar(connectionString, CommandType.Text, strSql, cmdParms));
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 批量执行SQL语句（事务）
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="sqlStrs">sql语句</param>
        /// <returns></returns>
        public static bool ExecuteSqlsTran(string connectionString, List<string> sqlStrs)
        {
            return ExecuteSqlsTran(connectionString, sqlStrs, null);
        }

        /// <summary>
        /// 批量执行SQL语句（事务）
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="sqlStrs">sql语句</param>
        /// <returns></returns>
        public static bool ExecuteSqlsTran(SqlConnection sqlConnection, List<string> sqlStrs)
        {
            if (sqlConnection.State != ConnectionState.Open)
                sqlConnection.Open();
            bool result = false;
            SqlCommand sqlcommand = new SqlCommand();
            SqlTransaction transaction = sqlConnection.BeginTransaction();
            sqlcommand.Transaction = transaction;
            sqlcommand.Connection = sqlConnection;

            sqlcommand.CommandTimeout = 1800;

            try
            {
                sqlcommand.CommandText = string.Join(";\n", sqlStrs);
                sqlcommand.ExecuteNonQuery();

                //foreach (var item in sqlStrs)
                //{
                //    sqlcommand.CommandText = item;
                //    sqlcommand.ExecuteNonQuery();
                //}                

                transaction.Commit();
                result = true;
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                result = false;
                throw ex;
            }
            finally
            {
                sqlcommand.Dispose();
            }

            return result;
        }
        /// <summary>
        /// 批量执行SQL语句（事务）
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="sqlStrs">sql语句</param>
        /// <param name="sqlParameterList">参数</param>
        /// <returns></returns>
        public static bool ExecuteSqlsTran(string connectionString, List<string> sqlStrs, List<List<SqlParameter>> sqlParameterList)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                return ExecuteSqlsTran(sqlConnection, sqlStrs, sqlParameterList);
            }
        }

        /// <summary>
        /// 批量执行SQL语句（事务）
        /// </summary>
        /// <param name="connectionString">链接</param>
        /// <param name="sqlStrs">sql语句</param>
        /// <param name="sqlParameterList">参数</param>
        /// <returns></returns>
        public static bool ExecuteSqlsTran(SqlConnection sqlConnection, List<string> sqlStrs, List<List<SqlParameter>> sqlParameterList)
        {
            if (sqlParameterList != null && sqlStrs.Count != sqlParameterList.Count)
            {
                throw new Exception("sql语句和参数数量不一致！");
            }
            if (sqlConnection.State != ConnectionState.Open)
                sqlConnection.Open();
            bool result = false;
            SqlCommand sqlcommand = new SqlCommand();
            SqlTransaction transaction = sqlConnection.BeginTransaction();
            sqlcommand.Transaction = transaction;
            sqlcommand.Connection = sqlConnection;

            sqlcommand.CommandTimeout = 1800;

            try
            {
                for (int i = 0; i < sqlStrs.Count; i++)
                {
                    sqlcommand.CommandText = sqlStrs[i];
                    if (sqlParameterList != null)
                    {
                        sqlcommand.Parameters.Clear();
                        if (sqlParameterList[i] != null)
                        {
                            foreach (var v in sqlParameterList[i])
                            {
                                if (v.Value == null) v.Value = DBNull.Value;
                                sqlcommand.Parameters.Add(v);
                            }
                        }
                    }
                    sqlcommand.ExecuteNonQuery();
                }

                transaction.Commit();
                result = true;
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                result = false;
                throw ex;
            }
            finally
            {
                sqlcommand.Dispose();
            }

            return result;

        }
        #region 获取数据实体

        /// <summary>
        /// 获取对象集合
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="commandText">sql语句</param>
        /// <returns></returns>
        public static List<T> ReaderToList<T>(string connectionString, string commandText)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                return ReaderToList<T>(connection, commandText);
            }
        }


        /// <summary>
        /// 获取对象集合
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="commandText">sql语句</param>
        /// <returns></returns>
        public static List<T> ReaderToList<T>(SqlConnection connection, string commandText)
        {
            using (SqlCommand command = new SqlCommand())
            {
                PrepareCommand(command, connection, null, CommandType.Text, commandText, null);
                SqlDataReader read = command.ExecuteReader(CommandBehavior.CloseConnection);

                // MySqlDataReader read = ExecuteDataReader(connection, CommandType.Text, commandText, null);
                using (read)
                {
                    return ReaderToList<T>(read);
                }
            }
        }

        private static List<T> ReaderToList<T>(SqlTransaction transaction, string commandText)
        {
            SqlCommand command = new SqlCommand();
            PrepareCommand(command, transaction.Connection, transaction, CommandType.Text, commandText, null);
            SqlDataReader read = command.ExecuteReader();

            //MySqlDataReader read = ExecuteDataReader(transaction, CommandType.Text, commandText, null);
            //return ReaderToList<T>(read);

            List<T> query = ReaderToList<T>(read);
            read.Close();
            return query;
        }

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="commandText">sql语句</param>
        /// <returns></returns>
        public static T ReaderToModel<T>(string connectionString, string commandText)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlDataReader read = ExecuteReader(connection, CommandType.Text, commandText, null);
                using (read)
                {
                    return ReaderToModel<T>(read);
                }
            }
        }

        private static T ReaderToModel<T>(SqlTransaction transaction, string commandText)
        {

            SqlCommand command = new SqlCommand();
            PrepareCommand(command, transaction.Connection, transaction, CommandType.Text, commandText, null);
            SqlDataReader read = command.ExecuteReader();

            // MySqlDataReader read = ExecuteDataReader(transaction, CommandType.Text, commandText, null);

            T query = ReaderToModel<T>(read);
            read.Close();
            return query;
        }

        private static List<T> ReaderToList<T>(IDataReader dr)
        {

            List<T> list = new List<T>();
            Type modelType = typeof(T);
            int count = dr.FieldCount;
            List<PropertyInfo> listNotNullPropertyInfo = GetPropertyInfos(count, dr, modelType);
            while (dr.Read())
            {
                T model = ReaderToModel<T>(dr, count, listNotNullPropertyInfo, modelType);

                list.Add(model);
            }
            return list;
        }

        private static List<PropertyInfo> GetPropertyInfos(int fieldCount, IDataReader dr, Type modelType)
        {
            List<PropertyInfo> list = null;
            List<string> drNameList = new List<string>();

            for (int i = 0; i <= fieldCount - 1; i++)
            {
                drNameList.Add(dr.GetName(i));
            }

            PropertyInfo[] property = modelType.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (property != null)
            {
                list = property.ToList().Where(c => !drNameList.Contains(c.Name)
                    && (c.PropertyType.Name == typeof(string).Name
                    || c.PropertyType.Name == typeof(String).Name
                    || c.PropertyType.Name == typeof(int).Name
                    || c.PropertyType.Name == typeof(Int32).Name
                    || c.PropertyType.Name == typeof(Int64).Name
                    || c.PropertyType.Name == typeof(decimal).Name)
                     ).ToList();
            }
            return list;
        }

        //这个类对可空类型进行判断转换，要不然会报错   
        private static object HackType(object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null)
                    return null;
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }

            object obj;

            try
            {
                obj = Convert.ChangeType(value, conversionType);
            }
            catch
            {
                obj = 0;//conversionType.ToString();
            }
            return obj;
        }

        private static bool IsNullOrDBNull(object obj)
        {
            return (obj == null || (obj is DBNull));
        }


        public static T ReaderToModel<T>(IDataReader dr)   //根据dr 返回一条记录
        {
            if ((dr as SqlDataReader).HasRows == false) return default(T);
            Type modelType = typeof(T);      //Type 是一个类型的基类
            int count = dr.FieldCount;       //得到适配器存放的表中的列的个数
            List<PropertyInfo> listNotNullPropertyInfo = GetPropertyInfos(count, dr, modelType);

            dr.Read();

            return ReaderToModel<T>(dr, count, listNotNullPropertyInfo, modelType);

        }

        private static T ReaderToModel<T>(IDataReader dr, int fieldCount, List<PropertyInfo> listNotNullPropertyInfo, Type modelType)
        {
            T model = Activator.CreateInstance<T>();   //创建一个T类型的事例 T类必须有无参数的构造函数
            //foreach (PropertyInfo item in listNotNullPropertyInfo)
            //{
            //    if (item.PropertyType.Name == typeof(string).Name)
            //    {
            //        item.SetValue(model, Convert.ChangeType("", item.PropertyType), null);
            //    }
            //    if (item.PropertyType.Name == typeof(int).Name
            //  || item.PropertyType.Name == typeof(Int32).Name
            //  || item.PropertyType.Name == typeof(Int64).Name
            //  || item.PropertyType.Name == typeof(decimal).Name)
            //    {
            //        item.SetValue(model, Convert.ChangeType(0, item.PropertyType), null);
            //    }
            //}
            for (int i = 0; i < fieldCount; i++)            //逐列对一条记录进行遍历
            {
                if (!IsNullOrDBNull(dr[i]))            // 如果不为空
                {
                    PropertyInfo pi = modelType.GetProperty(dr.GetName(i), BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    if (pi != null)
                    {
                        pi.SetValue(model, HackType(dr[i], pi.PropertyType), null);


                    }
                }
            }
            return model;
        }
        #endregion

    }

}